package com.xcw.jac;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class QRCodeGenerator {
    public static void main(String[] args) {
        String data = "我喜欢你"; // 要编码为二维码的数据
        String filePath = "qrcode.png"; // 生成的二维码图片保存的路径

        int width = 300; // 二维码图片的宽度
        int height = 300; // 二维码图片的高度
        String format = "png"; // 二维码图片的格式

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码为UTF-8

        try {
            BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);
            Path outputPath = FileSystems.getDefault().getPath(filePath);
            MatrixToImageWriter.writeToPath(matrix, format, outputPath);
            System.out.println("二维码已生成并保存到 " + filePath);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}